﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ebada.Server;
using Itop.GpsCar.Model;
using IBatisNet.Common;

namespace Itop.GpsCar.Web.CustomAdmin
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.txtLoginName.Focus();
            
            if (!Page.IsPostBack)
            {
                this.txtLoginPwd.Attributes.Add("value", "a");
            }

        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //Response.Redirect("/admin/desktop/main.aspx");

            string sLoginName = this.txtLoginName.Text.Trim();
            string sLoginPwd = this.txtLoginPwd.Text;
            string sUserInfo = string.Empty;

            if (sLoginName.Length==0)
            {
                ClientScriptManager cs1 = Page.ClientScript;
                cs1.RegisterStartupScript(typeof(Object), "alert", "alert('请输入用户名！');", true);
                return;
            }

            //免验证码登陆
            string sCode = Session["CheckCode"] == null ? "" : Session["CheckCode"].ToString();
            CheckCode.Text = sCode;

            if (CheckCode.Text.Trim() == sCode)
            {
                user curuser = GetUser(sLoginName, sLoginPwd);
                if (curuser != null)
                {
                    HttpCookie cookie = new HttpCookie("UserID", curuser.userid.ToString());
                    Response.Cookies.Add(cookie);
                    Response.Redirect("main.aspx");
                }
                else
                {
                    CheckCode.Text = string.Empty;
                    ClientScriptManager cs1 = Page.ClientScript;
                    cs1.RegisterStartupScript(typeof(Object), "alert", "alert('登录失败，请验证用户名或密码！');", true);
                }

            }
            else
            {
                ClientScriptManager cs3 = Page.ClientScript;
                cs3.RegisterStartupScript(typeof(Object), "alert", "alert('登录失败，附加码输入错误！');", true);
            }

        }

        private user GetUser(string username, string userpwd)
        {
            user resultuser = null;
            string sql = " where username='" + username + "' and password='" + userpwd + "'";
            IList<user> userlist = Global.SqlMapper.GetList<user>("SelectuserList",sql);
            if (userlist.Count>0)
            {
                resultuser = userlist[0];
            }
            return resultuser;

        }
    }
}
